#!/usr/bin/bash

set -o errexit

PATH=/opt/local/gnu/bin:/opt/local/bin:/opt/local/sbin:/usr/bin:/usr/sbin

# Munin plugins
MUNIN_PLUGIN_VERSION='0.18'
MUNIN_PLUGINS="
	cert_expire
	cputime
	df
	load
	uptime
	users
	proc_state
	vfs_bytes
	vfs_iops
	vfs_latency
	if_net0
	pkg_audit
	memory_cap
	swap_cap
	smf
	tcp
	udp
	ip_version
	nullmailer
"
mc_ver=20201230225800

## MUNIN
echo "* Create munin template file that will be used during mdata setup"
cp /opt/local/etc/munin/munin-node.conf /opt/local/etc/munin/munin-node.conf.tpl

echo "* Download and install community munin plugins (overwrite all other plugins)"
#curl -L https://github.com/drscream/smartos-munin-plugins/archive/v${MUNIN_PLUGIN_VERSION}.tar.gz | gtar xz -C /opt/local/lib/munin/plugins --strip-components=1
curl -L https://minio.itime.biz:4443/downloads/smartos-munin-plugins/v${MUNIN_PLUGIN_VERSION}.tar.gz | gtar xz -C /opt/local/lib/munin/plugins --strip-components=1

echo "* Activate munin plugins"
/opt/itime/bin/munin-node-plugins ${MUNIN_PLUGINS}

echo "* Remove unused logfiles"
rm -f /var/log/courier.log

echo "* Cleanup home/admin because of delegate dataset usage"
rm -rf /home/admin/.[^.]*

echo "* Cleaning up."
rm -rf /root/*

# Provide workaround for /.zonecontrol/metadata.sock issue
# https://github.com/joyent/smtools/issues/3
gsed -i 's:^rm -f /.zonecontrol/metadata.sock$:rm -f /.zonecontrol/metadata.sock || true:g' \
	/opt/local/bin/sm-prepare-image

echo "* fix df command in sm-summary"
# https://github.com/joyent/smtools/pull/5
sed -i \
    -e "s|df -B1 /tmp|df -k /tmp|" \
    -e "s|/1024/1024|/1024|" \
    /opt/local/bin/sm-summary

# add minio client
wget --no-check-certificate https://minio.itime.biz:4443/downloads/minio/client/solaris-amd64/mc.RELEASE.${mc_ver} -O /opt/local/bin/mc
chmod +x /opt/local/bin/mc

echo "* Prepare image"
sm-prepare-image -y
